package com.toman.ui.work.workshop;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.itheima.pulltorefreshlib.PullToRefreshBase;
import com.itheima.pulltorefreshlib.PullToRefreshScrollView;
import com.king.zxing.CaptureActivity;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.lzy.okhttputils.request.GetRequest;
import com.toman.Enum.BaseEnum;
import com.toman.Enum.NetworkEnum;
import com.toman.Enum.PermEnum;
import com.toman.Interfaces.NewBaseUrl;
import com.toman.JavaBean.FirstQualityDto;
import com.toman.JavaBean.StaticsCount;
import com.toman.MyApplication;
import com.toman.R;
import com.toman.Util.ActionCallback;
import com.toman.Util.BaseNetUtil;
import com.toman.Util.DefaultAcitonCallback;
import com.toman.Util.DialogUtils;
import com.toman.Util.IntentUtils;
import com.toman.Util.JsonExcludeNull;
import com.toman.Util.JsonUtils;
import com.toman.Util.PermissonUtils;
import com.toman.Util.SPUtils;
import com.toman.Util.ToastUtil;
import com.toman.Util.ViewUtil;
import com.toman.bean.DialogBean;
import com.toman.bean.ItemListBean;
import com.toman.toolbar.ToolBarActivity;
import com.toman.widget.ClearEditText;
import com.toman.widget.callback.StringLoadingCallback;

import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Request;
import okhttp3.Response;

import static com.toman.Interfaces.NewBaseUrl.SCANNING_CODE;


public class FirstInspectionActivity extends ToolBarActivity {
    CommonAdapter<FirstQualityDto> adapter;
    private List<FirstQualityDto> list = new ArrayList<>();
    private String auditStatus = "0";
    @BindView(R.id.et_search)
    ClearEditText etSearch;
    @BindView(R.id.tv_select)
    TextView tvSelect;
    @BindView(R.id.fl_et)
    RelativeLayout flEt;
    @BindView(R.id.tv_select0)
    TextView tvSelect0;
    @BindView(R.id.iv_select0)
    ImageView ivSelect0;
    @BindView(R.id.rl_select0)
    RelativeLayout rlSelect0;
    @BindView(R.id.tv_select1)
    TextView tvSelect1;
    @BindView(R.id.iv_select1)
    ImageView ivSelect1;
    @BindView(R.id.rl_select1)
    RelativeLayout rlSelect1;
    @BindView(R.id.ll_base)
    LinearLayout llBase;
    @BindView(R.id.cb_muti)
    CheckBox cbMuti;
    @BindView(R.id.btn_muti)
    Button btnMuti;
    @BindView(R.id.rl_muti)
    RelativeLayout rlMuti;
    @BindView(R.id.lv)
    RecyclerView lv;
    @BindView(R.id.mPullToRefreshScrollView)
    PullToRefreshScrollView mPullToRefreshScrollView;
    @BindView(R.id.mMangeNodata)
    TextView mMangeNodata;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first_inspection);
        ButterKnife.bind(this);
        initToolBar(BaseEnum.FIRSTINSPECTION.name);
        initView();

    }


    @Override
    protected void onResume() {
        super.onResume();
//        if (!StringUtils.isEmpty(getIntent().getStringExtra("status"))) {
//            setSelect(getIntent().getStringExtra("status"));
//        } else {
//            customer(1, 1, etSearch.getText().toString());
//        }
        customer(1, 1, etSearch.getText().toString());

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.toolbar_add_scan, menu);
        MenuItem menuItem = menu.findItem(R.id.menu_scan);
        MenuItem menuItem2 = menu.findItem(R.id.menu_add);
        menuItem.setVisible(true);
        if (!PermissonUtils.contains(this, BaseEnum.FIRSTINSPECTION.has(PermEnum.ADD))) {
            menuItem.setVisible(false);
            menuItem2.setVisible(false);
        }

        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_add:
//                        Bundle bundle = new Bundle();
//                        bundle.putString("id", getIntent().getStringExtra("id"));
                        IntentUtils.startActivity(FirstInspectionActivity.this, FirstInspectionAddActivity.class);

                        break;

                    case R.id.menu_scan:
                        if (ViewUtil.checkPer(FirstInspectionActivity.this)) {
                            Intent intent = new Intent(FirstInspectionActivity.this, CaptureActivity.class);
                            startActivityForResult(intent, SCANNING_CODE);
                        }
                        break;
                }
                return false;
            }
        });

        return true;
    }


    private void initView() {
        ViewUtil.permission(getApplicationContext(), BaseEnum.FIRSTINSPECTION.has(PermEnum.CHECK), rlMuti);
        initAdapter();
        etSearch.setHint("产线名称/品名");
        cbMuti.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

                for (int i = 0; i < list.size(); i++) {
                    list.get(i).setCheckStatus(b);
                }
                adapter.notifyDataSetChanged();
            }
        });
        adapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                List<FirstQualityDto> beanlist = adapter.getDatas();
                FirstQualityDto bean = beanlist.get(position);
                Bundle bundle = new Bundle();
                bundle.putSerializable("bean", bean);
                bundle.putString("status", bean.getAuditStatus());
                IntentUtils.startActivity(FirstInspectionActivity.this, FirstInspectionInfActivity.class, bundle);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        lv.setAdapter(adapter);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false) {
        };
        lv.setLayoutManager(linearLayoutManager);
        mPullToRefreshScrollView.setMode(PullToRefreshBase.Mode.BOTH);
        mPullToRefreshScrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                dialog=null;
                dialogList.clear();
                page = 2;
                customer(1, 1, etSearch.getText().toString().trim());
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                customer(page, 2, etSearch.getText().toString().trim());
                page += 1;


            }
        });
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                customer(1, 1, s.toString().trim());

            }
        });
    }

    private void initAdapter() {
        adapter = new CommonAdapter<FirstQualityDto>(this, R.layout.reuse_list_workshop, list) {
            @Override
            protected void convert(ViewHolder holder, FirstQualityDto item, final int position) {
                holder.setText(R.id.tv_time, item.getCreateTime());
//                holder.setText(R.id.tv_code, item.getSendworkorderEntity().getSendworkCode());
                holder.getView(R.id.tv_code).setVisibility(View.GONE);
                holder.getView(R.id.iv_status).setVisibility(View.GONE);
                holder.setText(R.id.tv_title1, "产线名称");
                holder.setText(R.id.tv_content1, item.getBeltlineName());
                holder.setText(R.id.tv_title2, "品名");
                holder.setText(R.id.tv_content2, item.getProductName());
                holder.setText(R.id.tv_title3, "型号");
                holder.setText(R.id.tv_content3, item.getProductMode());
                holder.setText(R.id.tv_title4, "质量状态");
                holder.setText(R.id.tv_content4, getResources().getStringArray(R.array.qualityStatus)[item.getStatus()]);
                holder.getView(R.id.btn_del).setOnClickListener(v -> BaseNetUtil.actionDialog(FirstInspectionActivity.this, NewBaseUrl.workshop_firstquality_delete, item.getId() + "", token, "删除" + BaseEnum.FIRSTINSPECTION.name, () -> customer(1, 1, etSearch.getText().toString())));
                holder.getView(R.id.btn_check).setOnClickListener(v -> CheckDialog(FirstInspectionActivity.this, "首件质检", "", item));

                holder.getView(R.id.ll_6).setVisibility(View.GONE);

                if (item.getAuditStatus().equals("0")) {
                    holder.setText(R.id.tv_time, item.getCreateTime());
                    ViewUtil.permissionNew(getApplicationContext(), BaseEnum.FIRSTINSPECTION.has(PermEnum.CHECK), holder.getView(R.id.cb_status));
                    ViewUtil.permissionNew(getApplicationContext(), BaseEnum.FIRSTINSPECTION.has(PermEnum.CHECK), holder.getView(R.id.btn_check));
                    ViewUtil.permissionNew(getApplicationContext(), BaseEnum.FIRSTINSPECTION.has(PermEnum.DELETE), holder.getView(R.id.btn_del));
                    holder.setText(R.id.tv_title5, "创建人");
                    holder.setText(R.id.tv_content5, item.getCreateUser().getRealName());
                    CheckBox checkBox = holder.getView(R.id.cb_status);
                    checkBox.setChecked(item.getCheckStatus());
                    checkBox.setOnCheckedChangeListener((buttonView, isChecked) -> item.setCheckStatus(isChecked));

                } else {
                    holder.setText(R.id.tv_time, item.getAuditTime());
                    holder.getView(R.id.cb_status).setVisibility(View.GONE);
                    holder.getView(R.id.btn_check).setVisibility(View.GONE);
                    ViewUtil.permissionNew(getApplicationContext(), BaseEnum.PLAN.has(PermEnum.DELETE), holder.getView(R.id.btn_del));
                    holder.setText(R.id.tv_title5, "审核人");
                    holder.setText(R.id.tv_content5, item.getAuditUser().getRealName());

                }


            }
        };
    }

    public void customer(Integer page, final Integer type, String search) {
        if (dialog != null) {
            dialog.dismiss();
        }


        GetRequest params = OkHttpUtils
                .get(NewBaseUrl.workshop_firstquality_list)
                .params("token", token)
                .params("key", search)
                .params("limit", NewBaseUrl.num).params("page", page.toString())
                .params("auditStatus", auditStatus);
        for (DialogBean bean: dialogList){
            params.params(bean.getSubmitName(),bean.getResult());
        }
                params.execute(new StringLoadingCallback(this,mPullToRefreshScrollView,search) {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "首件质检列表: " + result);
                        if (type == 1) {
                            list.clear();
                        }
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");ViewUtil.lagout(code,getApplicationContext());
                        if (code == 0) {
                            JSONObject Jpage = jsonObj.getJSONObject("page");

                            List<FirstQualityDto> jsonArray = new ArrayList<FirstQualityDto>(JsonExcludeNull.parseArrayExcludeNull(Jpage.getString("list"), FirstQualityDto.class));
                            list.addAll(jsonArray);

                            if (list.size() == 0) {
                                mMangeNodata.setVisibility(View.VISIBLE);
                            } else {
                                mMangeNodata.setVisibility(View.GONE);
                            }
                            adapter.notifyDataSetChanged();
                            StaticsCount count = JSON.parseObject(Jpage.getString("staticsCount"), new TypeReference<StaticsCount>() {
                            });
                            tvSelect0.setText("待审核(" + count.getCount0() + ")");
                            tvSelect1.setText("已审核(" + count.getCount1() + ")");

                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                        mPullToRefreshScrollView.onRefreshComplete();
                    }
                });
    }

    private void setStatus(String status) {
        switch (status) {
            case "0":
                auditStatus = "0";
                tvSelect0.setTextColor(getResources().getColor(R.color.button_blue));
                tvSelect1.setTextColor(getResources().getColor(R.color.black33));
                ivSelect0.setBackgroundColor(getResources().getColor(R.color.button_blue));
                ivSelect1.setBackgroundColor(getResources().getColor(R.color.white));
                customer(1, 1, etSearch.getText().toString());
                rlMuti.setVisibility(View.VISIBLE);

                break;
            case "1":
                auditStatus = "1";
                tvSelect1.setTextColor(getResources().getColor(R.color.button_blue));
                tvSelect0.setTextColor(getResources().getColor(R.color.black33));
                ivSelect1.setBackgroundColor(getResources().getColor(R.color.button_blue));
                ivSelect0.setBackgroundColor(getResources().getColor(R.color.white));
                rlMuti.setVisibility(View.GONE);
                customer(1, 1, etSearch.getText().toString());
                break;


        }
    }

    @OnClick({R.id.rl_select0, R.id.rl_select1, R.id.btn_muti})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_select0:
                setStatus("0");
                break;
            case R.id.rl_select1:
                setStatus("1");
                break;
            case R.id.btn_muti:
                if (ViewUtil.getMutiCheck(list) == null) {
                    ToastUtil.makeText(getApplicationContext(), "请至少选中一个可审核选项");
                } else {
                    DialogUtils.mutiCheckDialog(this, BaseEnum.FIRSTINSPECTION.name, NewBaseUrl.workshop_firstquality_verify_batch, ViewUtil.getMutiCheck(list), new ActionCallback() {
                        @Override
                        public void run() {
                            customer(1, 1, etSearch.getText().toString());
                        }
                    });
                }
                break;
        }
    }
    @OnClick(R.id.tv_select)
    public void onViewClicked() {
        showDialog();

    }
    public void showDialog() {
        if (dialog == null) {
            dialogList.clear();
            dialogList.add( new DialogBean("beltlineId","产线名称", 1, BaseNetUtil.base(this, NetworkEnum.BELTLINE, mCompanyId)));

            dialogList.add( new DialogBean("productId","品名", 1, BaseNetUtil.base(this, NetworkEnum.PRODUCT, mCompanyId)));

            dialogList.add( new DialogBean("status","质量状态", 1, getResources().getStringArray(R.array.qualityStatus)));


            dialog = DialogUtils.selectNewDialog(this, dialogList, new ActionCallback() {
                @Override
                public void run() {
                    customer(1, 1,"");
                    dialog.dismiss();

                }
            });
            dialog.show();
        } else {
            dialog.show();
        }
    }

    public void CheckDialog(Activity context, String title, String url, FirstQualityDto item) {
        LayoutInflater factory = LayoutInflater.from(context);
        //LayoutInflater是用来找layout文件夹下的xml布局文件，并且实例化
        final View view = factory.inflate(R.layout.reuse_item_select, null);
        TextView textView = view.findViewById(R.id.tv_qualified);
        textView.setText(getResources().getStringArray(R.array.qualityStatus)[item.getStatus()]);
        ViewUtil.click(textView);
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogUtils.showDialog(FirstInspectionActivity.this, "质量状态", getResources().getStringArray(R.array.qualityStatus), "", new DefaultAcitonCallback() {
                    @Override
                    public void run(ItemListBean bean1, Dialog dialog) {
                        item.setStatus(Integer.parseInt(bean1.getID()));
                        textView.setText(bean1.getName());
                        dialog.dismiss();
                    }
                });
            }
        });

        new android.support.v7.app.AlertDialog.Builder(context)
                //对话框的标题
                .setTitle("确认审核选中的" + title + "吗？")
                .setView(view)
                //设定显示的View
                //对话框中的“登陆”按钮的点击事件
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        check(item);
                    }

                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                // 设置dialog是否为模态，false表示模态，true表示非模态
                .setCancelable(true)
                //对话框的创建、显示
                .create().show();
    }

    private void check(FirstQualityDto item) {
        MyApplication myApplication;
        myApplication = MyApplication.getInstance();
        String token = (String) SPUtils.get(myApplication, "token", "");
        Map<String, String> map = new HashMap<String, String>();

        map.put("id", item.getId() + "");
        map.put("status", item.getStatus() + "");

        String str = JsonUtils.obj2JsonString(map);
        OkHttpUtils
                .post(NewBaseUrl.workshop_firstquality_verify)
                .headers("token", token)
                .params("id", item.getId() + "")
                .params("status", item.getStatus() + "")

                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "审核: " + result);
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");ViewUtil.lagout(code,getApplicationContext());

                        if (code == 0) {
                            ToastUtil.makeText(myApplication, jsonObj.getString("msg"));
                            customer(1, 1, etSearch.getText().toString());


                        } else {
                            ToastUtil.makeText(myApplication, jsonObj.getString("msg"));
                        }

                    }
                });
    }
}
